<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['pets:goods:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['pets:goods:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pets:goods:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['pets:goods:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="店铺" align="center" prop="shopName" />
      <el-table-column label="商品名称" align="center" prop="name" />
      <el-table-column label="价格/Kg" align="center" prop="price" />
      <el-table-column label="目标" align="center" prop="target" />
      <el-table-column label="轮播图" align="center" prop="banner" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.banner" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pets_goods" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="收货人" align="center" prop="receiver" />
<!--      <el-table-column label="收获地址" align="center" prop="address" />-->
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="160">
        <template slot-scope="scope">
          <span>{{ scope.row.updateTime }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="系统用户id" align="center" prop="sysUserId" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button
              v-show="scope.row.status==='上架'"
              size="mini"
              type="text"
              icon="el-icon-close"
              @click="offline(scope.row)"
              v-hasPermi="['pets:goods:edit']"
          >下架</el-button>
          <el-button
              v-show="scope.row.status==='下架'"
              size="mini"
              type="text"
              icon="el-icon-check"
              @click="online(scope.row)"
              v-hasPermi="['pets:goods:edit']"
          >上架</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['pets:goods:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['pets:goods:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1100px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="店铺" prop="shopId">
              <el-select v-model="form.shopId" placeholder="请选择店铺" style="width: 100%">
                <el-option
                    v-for="item in shopOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="目标" prop="target">
              <el-input v-model.number="form.target" placeholder="请输入目标" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格/Kg" prop="price">
              <el-input type="number" v-model="form.price" placeholder="请输入价格/Kg" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="价格模版" prop="priceTemplate">
              <el-select
                  v-model="form.priceTemplate"
                  multiple
                  filterable
                  allow-create
                  default-first-option
                  placeholder="请输入价格模版" style="width: 100%">
                <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="默认索引" prop="selectIndex">
              <el-input v-model.number="form.selectIndex" placeholder="请输入默认索引（从0开始）" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="助力文案" prop="assist">
              <el-input v-model="form.assist" placeholder="请输入助力文案" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="收货人" prop="receiver">
              <el-input v-model="form.receiver" placeholder="请输入收货人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入地址" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="商品主图" prop="mainImage">
              <image-upload v-model="form.mainImage"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="轮播图" prop="banner">
              <image-upload v-model="form.banner"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-for="(p, index) in form.param" :gutter="20">
          <el-col :span="10">
            <el-form-item label="参数名称" prop="paramName">
              <el-input v-model="p.key" placeholder="请输入参数名称" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="参数值" prop="paramValue">
              <el-input v-model="p.value" placeholder="请输入参数值" />
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" @click.prevent="addParam">新增</el-button>
          </el-col>
          <el-col :span="2">
            <el-button type="danger" @click.prevent="removeParam(p)">删除</el-button>
          </el-col>
        </el-row>

        <el-row v-for="(e, index) in form.ensure" :gutter="20">
          <el-col :span="10">
            <el-form-item label="保证名称" prop="ensureName">
              <el-input v-model="e.key" placeholder="请输入保证名称" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="保证内容" prop="ensureValue">
              <el-input v-model="e.value" placeholder="请输入保证内容" />
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" @click.prevent="addEnsure">新增</el-button>
          </el-col>
          <el-col :span="2">
            <el-button type="danger" @click.prevent="removeEnsure(e)">删除</el-button>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="20">
            <el-form-item label="折扣文案" prop="discounts">
              <el-input v-model="form.discounts" placeholder="请输入折扣文案" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="授权文案" prop="authText">
              <el-input v-model="form.authText" placeholder="请输入授权文案" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="授权图片" prop="authPics">
              <image-upload v-model="form.authPics"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="绑定用户" prop="sysUserId">
              <el-select v-model="form.sysUserId" placeholder="请选择用户" style="width: 100%">
                <el-option
                    v-for="item in userOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="商品介绍">
              <editor v-model="form.intro" :min-height="192" :height="500"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addGoods, delGoods, getGoods, listGoods, offline, online, updateGoods} from "@/api/pets/goods";
import {listShop} from "@/api/pets/shop";
import {listUser} from "@/api/system/user";
import {listPlatform} from "@/api/pets/platform";

export default {
  name: "Goods",
  dicts: ['pets_goods'],
  data() {
    return {
      shopOptions: [],
      userOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品表格数据
      goodsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
      },
      // 表单参数
      form: {
        discounts: null,
        mainImage: null,
        param: [],
      },
      options:[],
      // 表单校验
      rules: {
        shopId: [
          { required: true, message: "店铺id不能为空", trigger: "change" }
        ],
        name: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "价格/Kg不能为空", trigger: "blur" }
        ],
        banner: [
          { required: true, message: "轮播图不能为空", trigger: "blur" }
        ],
        param: [
          { required: true, message: "产品参数不能为空", trigger: "blur" }
        ],
        ensure: [
          { required: true, message: "商品保证不能为空", trigger: "blur" }
        ],
        authText: [
          { required: true, message: "授权文案不能为空", trigger: "blur" }
        ],
        authPics: [
          { required: true, message: "授权图片不能为空", trigger: "blur" }
        ],
        intro: [
          { required: true, message: "商品介绍不能为空", trigger: "blur" }
        ],
        // status: [
        //   { required: true, message: "状态 0-上架 1-下架不能为空", trigger: "change" }
        // ],
        sysUserId: [
          { required: true, message: "绑定用户不能为空", trigger: "change" }
        ],
        receiver: [
          { required: true, message: "收货人不能为空", trigger: "blur" }
        ],
        address: [
          { required: true, message: "收获地址不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getShopOption();
    this.getUserOption();
  },
  methods: {
    /** 查询商品列表 */
    getList() {
      this.loading = true;
      listGoods(this.queryParams).then(response => {
        this.goodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        shopId: null,
        name: null,
        price: null,
        banner: null,
        param: [{
          key: '',
          value: ''
        }],
        ensure: [
          {
            key: '',
            value: ''
          }
        ],
        authText: null,
        authPics: null,
        intro: null,
        status: 0,
        sysUserId: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getGoods(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品";
      });
    },

    offline(row) {
      this.reset();
      const id = row.id || this.ids
      offline(id).then(response => {
        this.$modal.msgSuccess("下架成功");
        this.getList();
      });
    },

    online(row) {
      this.reset();
      const id = row.id || this.ids
      online(id).then(response => {
        this.$modal.msgSuccess("上架成功");
        this.getList();
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateGoods(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGoods(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除商品编号为"' + ids + '"的数据项？').then(function() {
        return delGoods(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/goods/export', {
        ...this.queryParams
      }, `goods_${new Date().getTime()}.xlsx`)
    },

    getShopOption() {
      listShop().then(response => {
        this.shopOptions = response.rows.map(shop=>{
          return {
            "value": shop.id,
            "label": shop.name
          }
        })
      })
    },

    getUserOption() {
      listUser().then(response => {
        this.userOptions = response.rows.map(user=>{
          return {
            "value": user.userId,
            "label": user.nickName
          }
        })
      })
    },

    addParam(){
      this.form.param.push({
        key: '',
        value: ''
      })
    },

    addEnsure(){
      this.form.ensure.push({
        key: '',
        value: ''
      })
    },

    removeParam(item){
      let index = this.form.param.indexOf(item)
      if (index !== -1) {
        this.form.param.splice(index, 1)
      }
    },

    removeEnsure(item){
      let index = this.form.ensure.indexOf(item)
      if (index !== -1) {
        this.form.ensure.splice(index, 1)
      }
    }

  },
};
</script>
